import { defineStore } from 'pinia'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref } from 'vue'
import $ajax from '../api/to8081.js'
import $ajaxRole from '../api/to8080.js'
import { alertCode } from '@/utils/msg.js'

export const useMembers = defineStore('members', {
  state: () => ({
    /** @type {{ id:number, rname:String, nbl:number, remark:String }[]} */
    roles: [],
    role:'',
    members:[],
    curPage:1,
    pageSize:5,
    dialogVisible: false,
    rules:{
      tel: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        {
          pattern: /^1[3456789]\d{9}$/,
          message: '请输入正确的手机号格式',
          trigger: 'blur',
        },
      ],
      gender: [
        {
          required: true,
          message: '请选择性别',
          trigger: 'change',
        },
      ],
      roleid: [
        {
          required: true,
          message: '请选择角色',
          trigger: 'change',
        },
      ],
      mname: [{
        required: true,
        message: '请输入名字',
        trigger: 'blur',
      }]
    },
    roleForm:{
      mname:'',
      gender:'',
      tel:'',
      roleid:'',
      birth:''
},
    ruleRef:'',
  }),
  getters: {
    getRules(state) {
      return state.rules;
    },
    getRoles(state) {
      return state.roles;
    }
  },
  // 也可以这样定义
  // state: () => ({ count: 0 })
  actions: {
    async loadData() {
      if (this.members === null || this.members.length === 0) {
        const path = '/member/list'
        const res = await $ajax.get(path)
        console.log(res.data)
        if (res.code === 200) {
          this.members = res.data
        }
      }
    },
    async loadRole() {
      if (this.roles === null || this.roles.length === 0) {
        const path = '/role/list'
        const res = await $ajaxRole.get(path)
        console.log(res)
        if (res.code === 200) {
          this.roles = res.data
        }
        console.log(res)
      }
    },
    async stateChange(row) {
      console.log(row)
        const path = '/member/switch'
        const res = await $ajax.post(path, row)
        if (res.code === 200) {
          alertCode(200)
        }else {
          alertCode(400)
        }
      },
    openEdit() {
      this.dialogVisible = true
    },
    closeEdit() {
      this.dialogVisible = false
      this.roleForm = {
        mname:'',
        gender:'',
        tel:'',
        roleid:'',
        birth:''
      }
    },
    async saveForm() {
      const path = '/member/add'
      const res = await $ajax.post(path, this.roleForm)
      if (res.code === 200) alertCode(200);
    },

  }

})
